<?php

namespace app\admin\controller\health\user;

use app\common\controller\Backend;
use app\health\model\healthPro\Channel;
use app\health\model\healthPro\Product;
use app\health\model\HealthUser;
use app\health\model\HealthUserAccount;
use app\health\model\HealthUserChannel;
use app\health\model\HealthUserSignIn;
use app\health\service\ConfigService;
use think\Db;
use think\Exception;
use think\wenhainan\Thinkcsv;

class User extends Backend
{
    /**
     * @var null|HealthUser $model
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new HealthUser;
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $params    = $this->request->param();
            $condition = [];
            if (!empty($params['mobile'])) {
                $condition['mobile'] = ['like', '%' . $this->request->param('mobile') . '%'];
            }
            if (!empty($params['id_card']) && $params['id_card'] !== '') {
                if ((int)$params['id_card'] === 1) {
                    $condition['id_card'] = ['<>', ''];
                } else {
                    $condition['id_card'] = ['=', ''];
                }
            }
            $createdAt = $params['created_at'];
            $createdAt = array_filter(is_array($createdAt) ? $createdAt : [], static function ($value) {
                return !empty($value);
            });
            if (!empty($createdAt)) {
                $condition['created_at'] = ['between time', [$createdAt[0] . ' 00:00:00', $createdAt[1] . ' 23:59:59']];
            }
            if (!empty($params['channel_id'])) {
                $condition['id'] = ['in', HealthUserChannel::where('pid', 'in', $params['channel_id'])->column('user_id')];
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $list     = $this->model
                ->with(['userChannel', 'userRemain'])
                ->where($condition)
                ->order($sort, $order)
                ->paginate($limit);
            $userList = [];
            $channel  = Channel::column('id,name', 'id');
            $product  = Product::column('iden,name', 'iden');
            foreach ($list->items() as $v) {
                $userList[] = [
                    'id'                => $v['id'],
                    'mobile'            => $v['mobile'],
                    'avatar'            => $v['avatar'],
                    'real_name'         => $v['real_name'],
                    'id_card'           => $v['id_card'],
                    'virtually_coin'    => $v['virtually_coin'],
                    'balance'           => $v['balance'],
                    'sign_in_day_total' => $v['sign_in_day_total'],
                    'created_at'        => $v['created_at'],
                    'channel_name'      => $v->userChannel->pid ? $channel[$v->userChannel->pid] ?? '' : '',
                    'product_name'      => $v->userChannel->zf_code ? $product[$v->userChannel->zf_code] ?? '' : '',
                    'last_remain_date'  => date('Y-m-d', strtotime($v->user_remain->created_at))
                ];
            }
            $result = ["total" => $list->total(), "rows" => $userList];
            $this->success('查看用户', null, $result);
        }
        $channel = Channel::all();
        $this->assignconfig([
            'channel' => $channel
        ]);
        return $this->view->fetch();
    }

    public function export(): void
    {
        //如果发送的来源是Selectpage，则转发到Selectpage
        $params    = $this->request->param();
        $condition = [];
        if (!empty($params['mobile'])) {
            $condition['mobile'] = ['like', '%' . $this->request->param('mobile') . '%'];
        }
        if (!empty($params['id_card']) && $params['id_card'] !== '') {
            if ((int)$params['id_card'] === 1) {
                $condition['id_card'] = ['<>', ''];
            } else {
                $condition['id_card'] = ['=', ''];
            }
        }
        $createdAt = $params['created_at'];
        $createdAt = array_filter(is_array($createdAt) ? $createdAt : [], static function ($value) {
            return !empty($value);
        });
        if (!empty($createdAt)) {
            $condition['created_at'] = ['between time', [$createdAt[0] . ' 00:00:00', $createdAt[1] . ' 23:59:59']];
        }
        if (!empty($params['channel_id'])) {
            $condition['id'] = ['in', HealthUserChannel::where('pid', 'in', $params['channel_id'])->column('user_id')];
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list     = $this->model
            ->with(['userChannel'])
            ->where($condition)
            ->order($sort, $order)
            ->select();
        $userList = [];
        $channel  = Channel::column('id,name', 'id');
        $product  = Product::column('iden,name', 'iden');
        foreach ($list as $v) {
            $userList[] = [
                'id'           => $v['id'],
                'mobile'       => $v['mobile'],
                'isp'          => $v->userChannel->isp,
                'province'     => $v->userChannel->province . '-' . $v->userChannel->city,
                'channel_name' => $v->userChannel->pid ? $channel[$v->userChannel->pid] ?? '' : '',
                'product_name' => $v->userChannel->zf_code ? $product[$v->userChannel->zf_code] ?? '' : '',
                'real_name'    => $v['real_name'],
                'id_card'      => $v['id_card'],
                'created_at'   => date('Y-m-d', $v['created_at']),
            ];
        }
        //浏览器渲染导出csv
        $header = ['ID', '手机号', '手机运营商', '归属地', '来源渠道', '订购产品', '真实姓名', '身份证号码', '注册时间'];
        //浏览器访问渲染下载
        $csv = new Thinkcsv('用户列表-' . date('YmdHis') . '.csv', $header, $userList);
        $csv->export();
    }

    /**
     * 用户详情
     * @param [type] $id
     * @return string
     * @throws Exception
     * @Author 张旭鹏
     * @DateTime 2023-07-03
     */
    public function profile($id): string
    {
        $row = $this->model->get($id, ['userChannel']);
        if (!$row) {
            $this->error('未找到用户');
        }
        if ($this->request->isAjax()) {
            $this->success('用户详情', null, $row);
        }
        $row->user_channel->pid_name     = $row->user_channel->pid ? Channel::where('id', $row->user_channel->pid)->value('name') : '-';
        $row->user_channel->product_name = $row->user_channel->zf_code ? Product::where('iden', $row->user_channel->zf_code)->value('name') : '-';
        $this->assignconfig('row', $row);
        return $this->view->fetch();
    }

    /**
     * 更新信息
     * @Author 张旭鹏
     * @DateTime 2023-07-03
     */
    public function update(): void
    {
        $params = $this->request->post('data');
        $params = json_decode($params, true);
        $user   = $this->model->get($params['id']);
        if (!$user) {
            $this->error('未找到用户');
        }
        try {
            $user->avatar = $params['avatar'] ?? '';
            if ($user->avatar === cdnurl(ConfigService::getUserConfig('avatar'), true)) {
                $user->avatar = '';
            }
            $user->nickname = $params['nickname'] ?? '';
            $user->status   = $params['status'] ?? 1;
            $user->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('更新成功', null, $user);
    }

    /**
     * 账户记录
     * @Author 张旭鹏
     * @DateTime 2023-07-03
     */
    public function balance_log()
    {
        $user_id = $this->request->param('user_id');
        $limit   = $this->request->param('limit', 10);
        $model   = new HealthUserAccount();
        $data    = $model
            ->where(['user_id' => $user_id, 'account_type' => HealthUserAccount::ACCOUNT_TYPE_BALANCE])
            ->order('id desc')
            ->paginate($limit);
        $this->success('余额明细', null, $data);
    }

    /**
     * 签到记录
     * @Author 张旭鹏
     * @DateTime 2023-07-03
     */
    public function sign_in_record()
    {
        $user_id = $this->request->param('user_id');
        $limit   = $this->request->param('limit', 10);
        $model   = new HealthUserSignIn();
        $data    = $model
            ->where(['user_id' => $user_id])
            ->order('id desc')
            ->paginate($limit);
        $this->success('签到记录', null, $data);
    }
}
